<?php
/**
 * 全局共享寄存器
 * 提升程序效率，降低类耦合
 *
 * @package Request
 * @author Shuky
 * @since v1.0
 * @version $Id: Registry.php 104 2011-04-24 20:06:05Z shukyoo@gmail.com $
 */
namespace SF;

class Registry extends \ArrayObject
{
	protected static $_registry = null;
	protected static $_register = null;

	public function __construct()
	{
		parent::__construct(array(), parent::ARRAY_AS_PROPS);
	}


	public static function getInstance()
	{
		if (null === self::$_registry) {
			self::$_registry = new self();
		}
		return self::$_registry;
	}


	/**
	 * 设置一个默认装配类
	 */
	public static function setRegister($register)
	{
		self::$_register = $register;
	}


	/**
	 * 注册
	 */
	public static function set($index, $value)
	{
		$instance = self::getInstance();
		$instance->offsetSet($index, $value);
	}


	/**
	 * 获取
	 */
	public static function get($index, $item = '')
	{
		$instance = self::getInstance();
		if (!$instance->offsetExists($index)) {
			// 如果不存在，则尝试用默认装配类加载
			$register = self::$_register;
			$method = 'get'. ucfirst(strtolower($index));
			if ($register && method_exists($register, $method)) {
				self::set($index, call_user_func(array($register, $method)));
			} elseif ($item) {
                if (!is_object($item)) {
                    $item = new $item();
                }
                self::set($index, $item);
            } else {
				throw new Exception('索引项`'. $index .'`不存在');
			}
		}
		return $instance->offsetGet($index);
	}


	public static function isRegistered($index)
	{
		if (null === self::$_registry) {
			return false;
		}
		return self::$_registry->offsetExists($index);
	}
}
